import turtle
import sys


class RecursiveTriangle:
    def __init__(self, length=100, depth=1):
        self.length = length
        self.depth = depth
        self._init_position = (-self.length / 2, -self.length * 2/ 5)

        turtle.tracer(2, 1)

        self.tur = turtle.Turtle()
        self.tur.speed(0)
        self.tur.ht()
        self.tur.getscreen().bgcolor('cyan')
        self.tur.getscreen().onkeypress(self._exit, 'q')
        self.tur.getscreen().listen()

        self.tur.up()
        self.tur.setposition(self._init_position)
        self.tur.down()
        self.init_triangle()
        self._run()

    def init_triangle(self):
        self.tur.setheading(0)
        for i in range(3):
            self.tur.fd(self.length)
            self.tur.left(120)
        self.draw_inner_triangle(self._init_position, 1)

    def draw_inner_triangle(self, pos, depth):
        self.tur.up()
        self.tur.setposition(pos)
        self.tur.setheading(0)

        self.tur.fd(self.length / 2 ** depth)
        self.tur.setheading(60)
        self.tur.down()

        for i in range(3):
            self.tur.fd(self.length / 2 ** depth)
            self.tur.left(120)

        self.tur.up()
        self.tur.setposition(pos)
        self.tur.down()
        self.tur.setheading(0)

    def recursive_draw_triangle(self, pos, depth):
        if depth <= self.depth:
            for i in range(3):
                self.draw_inner_triangle(self.tur.position(), depth)
                self.recursive_draw_triangle(self.tur.position(), depth + 1)
                self.tur.setheading(i * 120)
                self.tur.up()
                self.tur.fd(self.length / 2 ** (depth - 1))
                self.tur.down()

    def _exit(self):
        sys.exit(0)

    def _run(self):
        if self.depth >= 2:
            self.recursive_draw_triangle(self.tur.position(), 2)

        self._save()
        turtle.done()

    def _save(self):
        self.tur.getscreen().getcanvas().postscript(file='out.eps')


RecursiveTriangle(500, 6)
